document.addEventListener('DOMContentLoaded', function() {
    // API基础URL
    const TAGS_API_URL = '/api/tags';

    // DOM元素
    const tagsContainer = document.getElementById('tagsContainer');
    const addTagBtn = document.getElementById('addTagBtn');
    const tagModal = document.getElementById('tagModal');
    const tagModalTitle = document.getElementById('tagModalTitle');
    const tagForm = document.getElementById('tagForm');
    const tagIdInput = document.getElementById('tagId');
    const tagNameInput = document.getElementById('tagName');
    const tagColorInput = document.getElementById('tagColor');
    const cancelTagBtn = document.getElementById('cancelTagBtn');

    // 当前编辑的标签ID
    let editingTagId = null;

    // 初始化
    init();

    function init() {
        fetchTags();

        // 事件监听
        addTagBtn.addEventListener('click', showAddTagModal);
        cancelTagBtn.addEventListener('click', hideTagModal);
        tagForm.addEventListener('submit', handleTagFormSubmit);
    }

    // 获取所有标签
    async function fetchTags() {
        try {
            const response = await fetch(TAGS_API_URL);

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const tags = await response.json();
            renderTags(tags);
            return tags;
        } catch (error) {
            console.error('Error fetching tags:', error);
            return [];
        }
    }

    // 渲染标签列表
    function renderTags(tags) {
        tagsContainer.innerHTML = '';

        if (tags.length === 0) {
            tagsContainer.innerHTML = '<p>暂无标签，请添加</p>';
            return;
        }

        tags.forEach(tag => {
            const tagItem = document.createElement('div');
            tagItem.className = 'tag-item';
            tagItem.innerHTML = `
                <span class="tag-color" style="background-color: ${tag.color}"></span>
                <span class="tag-name">${tag.name}</span>
                <div class="tag-actions">
                    <button class="tag-edit" data-id="${tag.id}">✏️</button>
                    <button class="tag-delete" data-id="${tag.id}">🗑️</button>
                </div>
            `;

            tagItem.querySelector('.tag-edit').addEventListener('click', () => editTag(tag.id));
            tagItem.querySelector('.tag-delete').addEventListener('click', () => deleteTag(tag.id));

            tagsContainer.appendChild(tagItem);
        });
    }

    // 显示添加标签模态框
    function showAddTagModal() {
        editingTagId = null;
        tagModalTitle.textContent = '添加新标签';
        tagForm.reset();
        tagIdInput.value = '';
        tagColorInput.value = '#4CAF50'; // 默认绿色
        showTagModal();
    }

    // 显示编辑标签模态框
    async function editTag(id) {
        try {
            const response = await fetch(`${TAGS_API_URL}/${id}`);

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const tag = await response.json();

            editingTagId = id;
            tagModalTitle.textContent = '编辑标签';
            tagIdInput.value = id;
            tagNameInput.value = tag.name;
            tagColorInput.value = tag.color;

            showTagModal();
        } catch (error) {
            alert('获取标签信息失败');
            console.error('Error fetching tag:', error);
        }
    }

    // 删除标签
    async function deleteTag(id) {
        if (!confirm('确定要删除这个标签吗？相关书签将不再关联此标签。')) return;

        try {
            const response = await fetch(`${TAGS_API_URL}/${id}`, {
                method: 'DELETE'
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            fetchTags();
            // 刷新书签列表以反映标签删除
            location.reload();
        } catch (error) {
            alert('删除标签失败');
            console.error('Error deleting tag:', error);
        }
    }

    // 处理标签表单提交
    async function handleTagFormSubmit(e) {
        e.preventDefault();

        const name = tagNameInput.value.trim();
        const color = tagColorInput.value;

        if (!name) {
            alert('标签名称是必填项');
            return;
        }

        const tagData = {
            name,
            color
        };

        try {
            let response;

            if (editingTagId) {
                // 更新标签
                response = await fetch(`${TAGS_API_URL}/${editingTagId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(tagData)
                });
            } else {
                // 创建标签
                response = await fetch(TAGS_API_URL, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(tagData)
                });
            }

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            hideTagModal();
            fetchTags();
            // 刷新书签列表以反映新标签
            location.reload();
        } catch (error) {
            alert(editingTagId ? '更新标签失败' : '添加标签失败');
            console.error('Error saving tag:', error);
        }
    }

    // 显示标签模态框
    function showTagModal() {
        tagModal.style.display = 'flex';
        document.body.style.overflow = 'hidden';
    }

    // 隐藏标签模态框
    function hideTagModal() {
        tagModal.style.display = 'none';
        document.body.style.overflow = 'auto';
    }
});